//
//  ContentView.swift
//  SwiftUIBook
//
//  Created by True on 2023/8/3.
//

import SwiftUI


let menuColor = Color(hex: "333")

struct ContentView: View {
    
    @ObservedObject var viewModel: BookAPPVM
    
    @State private var urlString: String = ""
    
    @State private var inputString: String = ""
    
    @State private var isRead: Bool = false {
        didSet {
            showTool = !isRead
        }
    }
    
    @State private var showTool: Bool = true
    
    @State private var showBooksPop = false
    
    @State private var showGoAlert = false
    
    @State private var showSaveAlert = false
    
    var body: some View {
        VStack(spacing: 0) {
            ZStack(alignment: .leading) {
                WebView(urlStr: $urlString)
                    .onDidFinish { urlString, html, nextAction in
                        print("ContentView onDidFinish --- ")
                        // print("\(urlString) -----\n\(html)")
                        if viewModel.curUrlStr != urlString {
                            viewModel.curUrlStr = urlString
                            viewModel.nextAction = nextAction
                            viewModel.dealNewHtml(html, isReading: isRead)
                        }
                    }
                
                if isRead {
                    TextViewerView(textString: viewModel.readText)
                        .onScrollToEnd {
                            print("ContentView onScrollToEnd --- ")
                            viewModel.requestNext()
                        }
                        .onTapGesture {
                            showTool = !showTool
                        }
                }
            }
            if showTool {
                Divider()
                toolContainer
            }
        }
        .onAppear {
            print("onAppear -----")
            let url = UserDefaults.standard.string(forKey: SaveKey.LAST_VIEW_URL.rawValue)
            if let url = url {
                urlString = url
            }
        }
        .onDisappear {
            print("onDisappear -----")
            UserDefaults.standard.setValue(viewModel.curUrlStr, forKey: SaveKey.LAST_VIEW_URL.rawValue)
        }
    }
    
    var toolContainer: some View {
        HStack(alignment: .center, spacing: 15) {
            Menu {
                ForEach(viewModel.sites) { site in
                    Button(site.name) {
                        urlString = site.urlString
                    }
                }
            } label: {
                Text("Sites")
                    .foregroundColor(menuColor)
            }
            .padding()
            .menuStyle(BorderlessButtonMenuStyle())
            .menuIndicator(.hidden)
            .fixedSize()
            
            
            Button {
                showBooksPop = true
            }label: {
                Text("Books")
            }
            .buttonStyle(BorderlessButtonStyle())
            .padding()
            .popover(isPresented: $showBooksPop) {
                Form {
                    ForEach(viewModel.books, id: \.self) { book in
                        Button(book.name) {
                            urlString = book.homePage
                        }
                        .buttonStyle(BorderlessButtonStyle())
                        #if os(macOS)
                        .contextMenu {
                            Button("Delete") {
                                viewModel.deleteBook(book)
                                showBooksPop = false
                            }
                        }
                        #endif
                    }
                    #if os(iOS)
                    .onDelete { indexSet in
                        viewModel.deleteBook(indexSet)
                    }
                    #endif
                    .padding()
                }
            }
            
            Button {
                showGoAlert = true
            } label: {
                Image(systemName: "magnifyingglass")
            }
            .buttonStyle(BorderlessButtonStyle())
            .padding()
            .alert("前往", isPresented: $showGoAlert) {
                TextField("输入网址", text: $inputString)
                Button("Go") {
                    urlString = inputString
                    inputString = ""
                }
                Button("Cancel") {
                    showGoAlert = false
                    inputString = ""
                }
            }
            
            Button {
                showSaveAlert = true
            } label: {
                Image(systemName: "star")
            }
            .buttonStyle(BorderlessButtonStyle())
            .padding()
            .alert("收藏", isPresented: $showSaveAlert) {
                TextField("输入书籍名", text: $inputString)
                Button("Save") {
                    let book = BookAPPData.Book(id: Date().timeIntervalSince1970, name: inputString, homePage: viewModel.curUrlStr)
                    viewModel.addBook(book)
                    inputString = ""
                }
                Button("Cancel") {
                    showSaveAlert = false
                    inputString = ""
                }
            }
            
            // Toggle直接binding @State变量，无法触发 didSet
            Toggle("Read", isOn: Binding(get: { isRead }, set: { isRead = $0 }))
                .padding()
            
        }
        .foregroundColor(menuColor)
        .frame(maxWidth: .infinity)
        .background(Color(hex: "ececec"))
        
    }
    
    
}


struct ContentView_Previews: PreviewProvider {
    
    private static var vm: BookAPPVM {
        let vm = BookAPPVM()
        return vm
    }
    
    static var previews: some View {
        ContentView(viewModel: vm)
    }
}
